package org.java.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Description 线程池测试DEMO
 * @Date 2024/8/29 10:44
 * @Created by 10574
 */
@Slf4j
public class ThreadPoolExecutorDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        tryCatchTest();
//        setUncaughtExceptionHandler();
        testAfterExecute();
    }

    public static void testAfterExecute() throws InterruptedException {
        final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 5, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10)){
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                log.error("thread...: {}, err:{}", Thread.currentThread().getName(), t.getMessage(), t);
            }
        };
        threadPoolExecutor.execute(new RunnableTask());
//        Thread.sleep(5000);
//        threadPoolExecutor.submit(new RunnableTask());
    }

    @Slf4j
    private static class RunnableTask implements Runnable {

        @Override
        public void run() {
            log.info("get into task");
            int i = 10 / 0;
        }
    }

    public static void tryCatchTest() {
        final ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new RunnableTask());
        executorService.submit(new RunnableTask());
    }

    public static void setUncaughtExceptionHandler() throws InterruptedException {
        ThreadFactory factory = (Runnable r) -> {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
                log.error("Thread: {} , err: {}", Thread.currentThread().getName(), e.getMessage(), e);
            });
            return t;
        };
        final ExecutorService executorService = new ThreadPoolExecutor(2, 5, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10), factory);
        executorService.submit(new RunnableTask());
        Thread.sleep(1000);
        executorService.execute(new RunnableTask());
    }

    @Slf4j
    private static class Runnable2Task implements Runnable {

        @Override
        public void run() {
            int i = 10 / 0;
        }
    }

    private static class CallableTask implements Callable<Object> {

        @Override
        public Object call() throws Exception {
            log.info("------------------开始执行任务------------------");
            int i = 10 / 0;
            log.info("------------------任务结束------------------");
            return null;
        }
    }
}
